<template>
  <div>
    <h3 class="title">
      <span v-if="formDis ===false && isEdit === false">新增商品</span>
      <span v-if="isEdit === true">编辑商品</span>
      <span v-if="formDis === true">查看详情</span>
    </h3>
    <el-form
      ref="prductForm"
      :disabled="formDis"
      :model="prductForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      style="margin-top: 20px;">
      <el-form-item :prop="formDis?'':'name'" label="商品名称">
        <el-col :span="8" >
          <el-input
            v-model="prductForm.name"
            placeholder="请输入商品名称"
            type="text"
            maxlength="50"
            show-word-limit
          />
        </el-col>
      </el-form-item>

      <hr>
      <el-form-item :class="formDis?'':'add_tip'" label="缩略图" prop="'cost'">
        <el-col :span="24" >
          <div style="width:302px" class="fl">
            <div class="thumbnail">
              <img v-show="prductForm.picUrl" :src="prductForm.picUrl" alt="">
            </div>
            <div v-if="!formDis" class="uploadBox">
              <vueCropper
                :img-list.sync="addForm.cover"
                :fixed-number="[16,8]"
                :limit="1"
                img-type="slt"
                class="upload-demo fl"
                @modalShowFn="getModalStatus" />
              <el-button v-show="prductForm.picUrl" class="btn_clear fr" size="small" type="info" @click="clearPic()">清除</el-button>
            </div>
          </div>
          <!-- <div class="fl tipBox">
            <p slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件</p>
          </div> -->
        </el-col>
      </el-form-item>

      <hr>
      <!-- {{ imgsCurData.url }} -->
      <!-- {{ prductForm }} -->
      <el-form ref="imgsCurData" :disabled="formDis" :inline="false" :model="imgsCurData" :rules="imgRules" label-width="120px" class="demo-prductForm">
        <div v-if="!formDis">
          <el-row>
            <el-col :span="7">
              <el-form-item class="add_tip" prop="url" label="轮播图片管理">
                <div class="lbImgBox">
                  <vueCropper
                    :cropper-model="imgsCurData.url"
                    :img-list.sync="addForm.cover"
                    :fixed-number="[16,8]"
                    :disabled="prductForm.goodsGalleryList.length>=5"
                    :limit="1"
                    class="upload-demo fl"
                    @modalShowFn="lbtFn" />
                  <!-- <el-button :disabled="prductForm.goodsGalleryList.length==5" class="fl" size="small" type="primary">点击上传</el-button> -->
                  <div v-if="prductForm.goodsGalleryList.length<=5" class="lbImgCon fr">
                    <img v-if="lbImgPath" :src="lbImgPath" class="lbImgPath" alt="">
                  </div>
                </div>
                <span class="el-upload__tip" style="height:20px;line-height:20px; margin-left:-100px;">最多上传5张图片</span>
              <!-- </el-upload> -->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="">
                <el-button :disabled="prductForm.goodsGalleryList.length>=5" size="medium" style="margin-left:-100px" type="primary" @click="addImg('imgsCurData')">添加</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <span v-if="formDis" class="lbTitle">轮播图管理</span>
        <el-row>
          <el-col :span="22" align="center">
            <table
              v-if="prductForm.goodsGalleryList.length"
              class="table">
              <thead>
                <tr>
                  <td>序号</td>
                  <td>图片</td>
                  <td>操作</td>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in prductForm.goodsGalleryList" :key="index" >
                  <td>{{ index + 1 }}</td>
                  <td><img :src="item.url" alt="" style="width:50px"></td>
                  <td>
                    <el-button
                      size="mini"
                      type="success"
                      @click="move(index, 'up')">上移</el-button>
                    <el-button
                      size="mini"
                      type="success"
                      @click="move(index, 'down')">下移</el-button>
                    <el-button
                      size="mini"
                      type="danger"
                      @click="deleteFn(index)">删除</el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-col>
        </el-row>
        <hr>
        <!-- {{ prductForm }} -->
        <el-form-item :prop="formDis?'':'detail'" :class="formDis?'':'add_tip'" label="商品详情" class="">
          <div style="width:98%">
            <div v-if="formDis" class="tin_box" v-html="prductForm.detail" />
            <tinymce v-else v-model="prductForm.detail" :height="260" :disabled="tinymceDis" :value="prductForm.detail" />
          </div>
        </el-form-item>
      </el-form>
      <hr>
      <!-- {{ prductForm }} -->
      <el-form-item>
        <!-- 编辑 -->
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('prductForm')">确定</el-button>
        <!-- 新增 -->
        <el-button v-preventReClick v-if="!isEdit && !formDis" type="primary" @click="submitForm('prductForm')">确定</el-button>
        <!-- 取消 -->
        <el-button v-preventReClick v-if="!formDis" :disabled="false" @click="$router.go(-1)">关闭</el-button>
      </el-form-item>

    </el-form>
    <div class="bottomDiv">
      <el-button v-preventReClick v-if="formDis" @click="$router.go(-1)">关闭</el-button>
    </div>
  </div>
</template>

<script>
import config from '@/utils/config';
import Tinymce from '@/components/Tinymce'
import { Message } from 'element-ui'
import { goodsAdd, getGoodInfo } from '@/api/prductWenc'
import vueCropper from '@/components/cropper'
import UploadImg from '@/components/cropper/uploadImage.vue'

export default {
  components: { Tinymce, vueCropper, UploadImg },
  data() {
    return {
      addForm: {},
      imgsCurData: {
        url: '',
        picName: ''
      },
      isUpload: true, // 控制轮播图按钮
      prductForm: {
        name: '', // 商品名称
        picUrl: '', // 缩略图
        goodsGalleryList: [], // 轮播图
        detail: '' // 商品详情
      },
      list: [],
      lbImgPath: '',
      imgRules: {
        url: [
          { required: true, message: '请选择一张图片', trigger: 'blur' }
        ],
        picName: [
          { required: true, message: '请输入与图片相对应的名称', trigger: 'blur' },
          { max: 20, message: '输入字符不得超过20个', trigger: 'blur' },
          { pattern: /^[A-z0-9\u4e00-\u9fa5]*$/, message: '不能含有特殊字符', trigger: 'blur' }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        //   { pattern: /^[A-z0-9\u4e00-\u9fa5]*$/, message: '不能含有特殊字符', trigger: 'blur' }
        ]
      },
      // : [], // 缩略图
      fileList: [],
      actionUrl: config.BaseUrl + '/storage/create',
      thumbnailsUrl: config.BaseUrl + '/storage/create/thumbnails',
      //   SLTData: {
      //     width: '320',
      //     height: '320'
      //   },
      LBTData: {
        width: '1080',
        height: '644'
      },
      formDis: false,
      tinymceDis: false,
      isEdit: false,
      num: 0
    }
  },
  computed: {
    ruleForm: function() {
      return this.$store.getters.ruleForm
    }
  },
  watch: {
  },
  created() {
  },
  mounted() {
    const _self = this;
    console.log('this.$route.query:', JSON.stringify(this.$route.query))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      console.log(this.$route.query)
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
      this.formDis = Boolean(this.$route.query.isLook)
      this.tinymceDis = Boolean(this.$route.query.isLook)
      if (this.$route.query.isEdit) {
        this.specificationType = 'isEdit'
      }
      if (this.$route.query.isLook) {
        this.specificationType = 'formDis'
        console.log('mounted时router.query', this.$route.query.id)
        this.getGoodInfoFn(this.$route.query.id)
      }
    } else {
      // 查询会员类别（及每个类别下的会员等级信息）
    }
    // this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    getGoodInfoFn(id) {
      getGoodInfo({ id }).then(res => {
        if (res.code === '200') {
          console.log('查询商品详情：', res.data)
          this.prductForm = res.data
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    lbtFn(url) {
      this.isUpload = false
      this.lbImgPath = url
      this.imgsCurData.url = url
    },
    getModalStatus(url) {
      this.prductForm.picUrl = url
    },
    // 轮播图添加图片
    addImg(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          this.prductForm.goodsGalleryList.push(this.imgsCurData)
          this.imgsCurData = {}
          this.isUpload = true
          this.lbImgPath = ''
        } else {
          this.validateError()
          return false;
        }
      });
    },
    // 上移、下移
    move(index, type) {
      if (this.prductForm.goodsGalleryList.length) {
        if (index === 0 && type === 'up') return Message.error('第一个无法上移')
        if (index === this.prductForm.goodsGalleryList.length - 1 && type === 'down') return Message.error('最后一个无法下移动')
        const obj = this.prductForm.goodsGalleryList.splice(index, 1)
        if (type === 'up') this.prductForm.goodsGalleryList.splice(index - 1, 0, obj[0])
        if (type === 'down') this.prductForm.goodsGalleryList.splice(index + 1, 0, obj[0])
      }
    },
    // 轮播图删除
    deleteFn(index) {
      this.$confirm('确定删除此商品？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.prductForm.goodsGalleryList.splice(index, 1)
      })
    },
    request(data) {
      goodsAdd(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('新增成功')
          this.$router.push('index');
        } else {
          Message.error(response.message + '-' + response.data)
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.prductForm.picUrl)
          if (!this.prductForm.picUrl) {
            Message.error('请添加缩略图片')
            return false
          }

          if (!this.prductForm.goodsGalleryList.length) {
            Message.error('请添加轮播图片')
            return false
          }
          console.log('request')
          this.request(this.prductForm)
        } else {
          this.validateError()
          return false;
        }
      });
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      console.log('file:::', file)
      console.log('fileList:::', fileList)
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // let index = fileList
          console.log()
        })
      }
    },
    // 删除缩略图
    clearPic() {
      this.$confirm('确定删除此图吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.prductForm.picUrl = ''
        this.$refs.picUpload.clearFiles()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
    body {
        overflow: visible !important;
    }
    .fl{
        float: left;
    }
    .fr {
        float: right
    }
    hr{
        border: none;
        border-top: 1px solid #ddd;
        margin: 30px 0;
    }
    .table{
        width: 90% !important;
        margin-left:120px;
        font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
        text-rendering: optimizeLegibility;
        font-size: 14px;
        font-weight: 500;
        color: #606266;
        border-collapse: collapse;
    }
    .table td {
        text-align: center;
        border: 1px solid #ddd;
        padding: 10px 0;
    }
    .title{
        margin: 30px;
        color:#333;
    }
    .el-table__header tr,
    .el-table__header th {
        padding: 0;
        height: 30px !important;
    }
    .el-table__body tr,
    .el-table__body td {
        padding: 0 !important;
        height: 30px !important;
    }
    .el-table td, .el-table th {
        padding: 0 !important;
    }
    .tipBox{
        margin-top: 100px;
        margin-left: 10px;
    }
    .thumbnail{
        width: 302px;
        height: 151px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
        // flex-item-align: center;
    }

    .thumbnail img{
        width: 100% ;
    }
    .uploadBox{
        width: 100%;
        position: relative;
    }
    .btn_clear{
        position: absolute;
        bottom: -38px;
        right: 0;
        padding: 10px 30px;
    }

    .productName{
        width:300px
    }

    // .table{
    //     width: 100%;
    //     border-collapse: collapse;
    //     border-spacing: 0;
    // }
    // .table td{
    //     border: 1px solid #ddd;
    //     padding: 5px 10px;
    // }

  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }
  .el-upload-list, .el-form-item__content{
        display: none;
    }
    .el-upload-list{
        width: 50px;
        overflow: hidden;
    }

    .discontIpt{
        width:58%
    }

    .redBroder {
        border: 1px solid red;
        box-sizing: border-box;
        border-radius: 4px;
        transition: all .5s;
    }

    .lbImgCon{
        width:60px;
        height: 40px;
        border: 1px dashed #ddd;
        margin-top: 0px;
    }

    .lbImgPath{
        display: inline-block;
        width: 100%;
        height: 100%;
    }
    .lbImgBox{
        width:146px;
        overflow: hidden;
        vertical-align: top;
        padding-top: 4px;
    }
    .lbTitle{
        margin: 0 0 40px 4.5%;
        line-height: 50px;
        font-size: 14px;
    }
    .bottomDiv{
        padding:0 0 20px 11%;
    }

    .setting_ul{
        margin:0;
        padding:0;
        .title{
            width: 100%;
            height: 40px;
            line-height: 40px;
        }
    }
    .collapseItem{
        margin-left: 20px;
    }
</style>
